/*
 * 标签管理
 * @author 雷鸣
 * @time 2018/9/25
 * @since 1.0.0
 * */
// React基础组件
import React from 'react'
// dva 连接组件 - 连接route和model
import { connect } from 'dva'
import FlagBtn from 'widget/FlagBtn/FlagView'
// 引入antd的组件
import { Form, Select, Button, Modal, Row, Col, Input, Popconfirm } from 'antd'
const FormItem = Form.Item;
const { TextArea } = Input;
const confirm = Modal.confirm;
//导入路由组件，用于跳转等
import { Link, hashHistory } from 'dva/router'
// 导入项目全局配置文件
import config from 'config/config'

// 引入model取值工具方法
import { mapStateToProps } from 'utils/view_utils'
// 当前组件样式
import styles from './labelListStyle.less'
//引用listPage
import ListPage from 'widget/PageTmpl/ListPage'
import cx from 'classnames'

const Option = Select.Option;
/**
 * description 路由视图及事件处理
 * dispatch 分发到models中的effects对应事件名
 * model 用于获取models中state定义的数据
 * form 表单对象
 */

const labelListAdminView = function ({ dispatch, model, form }) {

  const { resetFields, getFieldDecorator, validateFields, setFieldsValue } = form
  const { modelObj, namespace } = model
  console.log("labelListModal=", modelObj)

  let { showTabelModal, modalTitle, detailData, actionType } = modelObj

  const formItemLayout = {
    labelCol: { span: 5 },
    wrapperCol: { span: 19 },
  };

  //新建/编辑标签
  function showModal(actionType, item) {
    resetFields()
    if (actionType == 'add') {
      dispatch({
        type: `${namespace}/updateModel`,
        payload: {
          showTabelModal: true,
          modalTitle: '新建标签',
          actionType: "add",
          detailData: {
            labelList: [],
            type: '',
            name: "",
            tagId: ""
          },
        }
      });
    } else if (actionType == 'edit') {

      detailData.tagId = item.tagId
      detailData.name = item.name
      detailData.type = item.type
      dispatch({
        type: `${namespace}/updateStore`,
        payload: { detailData }
      });
      dispatch({
        type: `${namespace}/updateModel`,
        payload: { showTabelModal: true, modalTitle: '编辑标签', actionType: "edit"}
      });
    }
  }
  
  //新建/编辑确定
  function handleOk() {
    validateFields((err, values) => {
      if (err) {
        return false
      }
      if (detailData.tagId) {
        dispatch({
          type: `${namespace}/update`,
          payload: {}
        });
      } else {
        dispatch({
          type: `${namespace}/labelAdd`,
          payload: {}
        });
      }
    })
  }

  //新建/编辑取消
  function handleCancel() {
    dispatch({
      type: `${namespace}/updateModel`,
      payload: { showTabelModal: false }
    });
  }

  //删除标签
  function deleteLabel(tagId) {
    dispatch({
      type: `${namespace}/labelDel`,
      payload: { tagId }
    });
  }


  //选择类型
  function handleChange(value) {
    detailData.type = value
    dispatch({
      type: `${namespace}/updateStore`,
      payload: { detailData }
    })
  }
  //修改标签名称
  function inputUpdateChange(value) {
    detailData.name = value
    dispatch({
      type: `${namespace}/updateStore`,
      payload: { detailData }
    })
  }
  
  //编辑标签名称
  function inputChange(value) {
    let arr = value.replace(/[\n\r|\n](?:[\n\r|\n])/mg,'').split(/[\r\n|\n]/)
    arr=arr.slice(0,6)
    detailData.labelList = arr
    dispatch({
      type: `${namespace}/updateStore`,
      payload: { detailData }
    })
  }
  let pageProps = {
    // ---------- 界面部分 ----------
    "ui": {
      "api_url": "admin/label/queryList",
      "method": "POST",
      "app": "",
      "params": "pageNo=1&pageSize=10",
      "mockData": null,
      "search_bar": {
        "fields": [
          {
            en_name: 'type',
            zh_name: '标签类别',
            elem_type: 'Select',
            elem_valid_type: 'string',
            cmpt_items: [
              {
                value: '',
                label: '全部'
              },
              {
                value: '1',
                label: '楼盘'
              },
              {
                value: '2',
                label: '户型'
              },
              {
                value: '3',
                label: '资讯'
              },
            ],
          }
        ],
        searchHandler: () => { // 自定义搜索按钮回调函数，点击搜索时触发
          console.log('search click')
        },
        resetHandler: () => { // 自定义重置按钮回调函数，点击重置时触发
          console.log('reset click')
        },
        searchCallback: params => { // 自定义搜索完成后的后调函数, 搜索完成后触发, 并将本次搜索的参数传入
          console.log('search finish', params)
        },
        pasteTargetList: [  // 列表组件中将输入框的en_name作为默认id(也可以通过id另外设置)
          'carName',  // 将需要粘贴事件拦截的输入框id以数组的形式传入, 该参数对应PasteFromClipboard组件的targetList参数
        ]
      },
      // 数据表格
      "table":
      {
        "status_params": "status=0",
        "status_text": "全部",
        // 表头字段列表
        "scroll": { x: 1000 },
        "fields": [
          {
            "en_name": "key",
            "zh_name": "序号",
            "width": "60",
            render: (a, item, index, d, e, f) => {
              return index + 1
            },
          },
          {
            "en_name": "name",
            "zh_name": "标签名称",
            width:130,
          },
          {
            "en_name": "type",
            "zh_name": "所属类别",
            width:60,
            render: (a, item, index) => {
              let text = ""
              if (item.type + '' === "1") {
                text = "楼盘"
              } else if (item.type + '' === "2") {
                text = "户型"
              } else if (item.type + '' === "3") {
                text = "资讯"
              }else if (item.type + '' === "4") {
                text = "秒杀"
              }else if (item.type + '' === "5") {
                text = "竞拍"
              }
              return (
                <span>{text}</span>
              )
            },
          },
          {
            en_name: "createPerson",
            zh_name: "创建人",
            width:100,
          },
          {
            en_name: "createTime",
            zh_name: "创建时间",
            width:180
          },
          {
            en_name: "updatePerson",
            zh_name: "更新人",
            width:100,
          },
          {
            en_name: "updateTime",
            zh_name: "更新时间",
            width:180
          },
          {
            en_name: "edit",
            zh_name: "操作",
            width:120,
            render: (a, item, index) => {
              return (

                <span >
                  {/*<Popconfirm  Collapse title='确定要删除吗？' okText='确定' cancelText='取消' onConfirm={() => { deleteLabel(item.tagId) }}>*/}

                     {/**/}
                  {/*</Popconfirm>*/}
 <FlagBtn
     node={<Popconfirm  Collapse title='确定要删除吗？' okText='确定' cancelText='取消' onConfirm={() => { deleteLabel(item.tagId) }}>
       <a >删除<span className="ant-divider" /></a>
     </Popconfirm>}
     btnId={'30403'}>
                    </FlagBtn>
                   <FlagBtn
                       node={ <a onClick={() => showModal('edit', item)}>编辑</a>}
                       btnId={'30402'}
                   >
                   </FlagBtn>
                </span>

              )
            },
          }
        ]
      },
      "action_bar": [{
        label: '新建',
        type: 'primary',
        btnId:'30401',
        onClick: (e, row) => {
          showModal('add')
        }
      }]
    },
  }
  if (!!modelObj.biz) {
    pageProps.biz = modelObj.biz
    pageProps.biz.syncBackCbf = (biz) => {
      dispatch({
        type: `${namespace}/setFormVal`,
        payload: biz
      })
    }
  }
  return (
    <div className={cx('pageLayout')}>
      <ListPage pageProps={pageProps} />
      <Modal
        title={modalTitle}
        visible={showTabelModal}
        onOk={()=>{console.log('131212');handleOk()}}
        onCancel={handleCancel}
      >
        <Row>
          <Col className="col" span={22}>
            <FormItem {...formItemLayout}
              label="所属类型">
              {getFieldDecorator('type', {
                initialValue: detailData.type+"",
                rules: [
                  { required: true, whitespace: true, message: '请选择类型' },
                ],
              })((<Select placeholder="请选择" onChange={handleChange} disabled={actionType=='edit'}>
                <Option value="1">楼盘</Option>
                <Option value="2">户型</Option>
                <Option value="3">资讯</Option>
              </Select>))}
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col className="col" span={22}>
            <FormItem {...formItemLayout}
              label="标签名称"
            >
              {getFieldDecorator('label', {
                initialValue: detailData.name,
                rules: [
                  { required: true, whitespace: true, message: '请输入标签' },
                  {validator: function (rule, value, callback){
                    let str=value.split(/[\r\n|\n]/)
                      let errorMsg=''
                      str.map((item)=>{
                        if(item.trim().length>6){
                          errorMsg='每行一个标签名称，可多行。每行最多输入6个字'
                        }
                      })
                      if(errorMsg){
                        callback(errorMsg)
                      }else{
                        callback()
                      }
                    }}
                ],
              })(actionType == "add" ? <TextArea
                style={{ height: '200px' }}
                rows={4}
                placeholder={'每行一个标签名称，可多行。每行最多输入6个字'}
                onChange={(e) => { inputChange(e.target.value, 'label') }}
              /> : <Input
                  onChange={(e) => { inputUpdateChange(e.target.value, 'commission') }}
                />)}
            </FormItem>
          </Col>
        </Row>
      </Modal>
    </div>
  )
}

// 连接视图(view)和模型(model)
export default connect(mapStateToProps)(Form.create()(labelListAdminView))
